package org.budo.support.servlet.filter.serverinfo;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.budo.support.java.net.util.JavaNetUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author limingwei
 */
public class ServerInfoResponseHeaderFilter implements Filter {
    private static final Logger log = Slf4j.getLogger();

    private static final String HEADER_NAME = "ServerInfo";

    private String serverInfoValue;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("#23 init this=" + this);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader(HEADER_NAME, this.getServerInfoValue());
        chain.doFilter(request, httpResponse);
    }

    private String getServerInfoValue() {
        if (null != this.serverInfoValue) {
            return this.serverInfoValue;
        }

        this.serverInfoValue = StringUtil.join(JavaNetUtil.getIpAddresses());
        return this.serverInfoValue;
    }

    @Override
    public void destroy() {
        log.info("#31 destroy this=" + this);
    }
}